package org.kzwl.service.app.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kzwl.comm.advice.BizException;
import org.kzwl.comm.advice.Consts;
import org.kzwl.comm.pojo.bo.live.GetStreamUrlBO;
import org.kzwl.comm.pojo.bo.live.LiveNotifyBO;
import org.kzwl.comm.pojo.dto.live.GetLiveBackDTO;
import org.kzwl.comm.pojo.dto.live.GetStreamUrlDTO;
import org.kzwl.comm.pojo.dto.live.LiveBasicDTO;
import org.kzwl.comm.utils.AliUtils;
import org.kzwl.comm.utils.MyUtils;
import org.kzwl.comm.utils.PagingCondition;
import org.kzwl.entity.app.CuLive;
import org.kzwl.entity.app.CuPlayback;
import org.kzwl.entity.app.User;
import org.kzwl.mapper.app.LiveMapper;
import org.kzwl.mapper.app.PlaybackMapper;
import org.kzwl.mapper.app.UserMapper;
import org.kzwl.service.app.LiveService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;

@Service
public class LiveServiceImpl  extends ServiceImpl<LiveMapper, CuLive> implements LiveService {

    @Autowired
    private LiveMapper liveMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PlaybackMapper playbackMapper;

    //region 查询直播
    @Override
    public IPage<LiveBasicDTO> queryBasic(PagingCondition bo) {
        IPage<CuLive> page = new Page<>();
        page.setCurrent(bo.getCurrent()).setSize(bo.getSize());
        page = liveMapper.selectPage(page,null);
        IPage<LiveBasicDTO> answer = new Page<>();
        BeanUtils.copyProperties(page,answer);
        answer.setRecords(JSONObject.parseArray(JSONObject.toJSONString(page.getRecords()),LiveBasicDTO.class));
        return answer;
    }

    //endregion

    //region 获得直播推流
    @Override
    public GetStreamUrlDTO getPushUrl(GetStreamUrlBO bo) {
        User user = userMapper.selectById(bo.getCuUserId());
        if (user.getCuUserIsLive()==0){
            throw new BizException("当前用户无直播发起权限");
        }
        QueryWrapper<CuLive> queryWrapper = new QueryWrapper<>();
        //暂时默认返回第一个直播间
//        queryWrapper.lambda().eq(CuLive::getCuUserId,bo.getCuUserId());
        queryWrapper.lambda().last(" limit 1");
        CuLive cuLive = liveMapper.selectOne(queryWrapper);
        cuLive.setIsShow(1);
        cuLive.setCuLiveTitle(bo.getCuLiveTitle());
        liveMapper.updateById(cuLive);
        long exp = System.currentTimeMillis() / 1000 + 1 * 3600;
        Map<String, String> map = AliUtils.aAuth(Consts.AliLive.PUSHURL + cuLive.getCuLiveAppName() + "/" + cuLive.getCuLiveStreamName(), Consts.AliLive.PUSHURLKEY, exp, cuLive.getCuLiveStreamName());
        GetStreamUrlDTO dto = new GetStreamUrlDTO();
        dto.setAuth(map.get("auth"));
        dto.setStreamName(map.get("streamName"));
        dto.setUrl(map.get("url"));
        dto.setIsShow(cuLive.getIsShow());
        return dto;
    }
    //endregion

    //region 获得直播间拉流
    @Override
    public GetStreamUrlDTO getPullUrl(GetStreamUrlBO bo) {
        //暂时默认返回第一条
        QueryWrapper<CuLive> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(CuLive::getCuLiveId,bo.getCuLiveId());
        queryWrapper.lambda().last(" limit 1");
        CuLive cuLive = liveMapper.selectOne(queryWrapper);
        if (cuLive==null){
            throw new BizException("未找到直播间资源");
        }
        long exp = System.currentTimeMillis() / 1000 + 1 * 3600;
        Map<String, String> map = AliUtils.aAuth(Consts.AliLive.PULLHURL + "/"+cuLive.getCuLiveAppName() + "/" + cuLive.getCuLiveStreamName(), Consts.AliLive.PULLHURLKEY, exp, cuLive.getCuLiveStreamName());
        GetStreamUrlDTO dto = new GetStreamUrlDTO();
        dto.setAuth(map.get("auth"));
        dto.setStreamName(map.get("streamName"));
        dto.setUrl(map.get("url"));
        dto.setIsShow(cuLive.getIsShow());
        return dto;
    }
    //endregion

    //region 停止直播
    @Override
    public void stopLive() {
        //暂时默认返回第一条
        QueryWrapper<CuLive> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(CuLive::getCuLiveId,bo.getCuLiveId());
        queryWrapper.lambda().last(" limit 1");
        CuLive cuLive = liveMapper.selectOne(queryWrapper);
        cuLive.setIsShow(0);
        liveMapper.updateById(cuLive);
    }
    //endregion

    //region
    @Transactional
    @Override
    public void liveNotify(LiveNotifyBO bo) {
        CuPlayback playback = new CuPlayback();
        QueryWrapper<CuPlayback> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CuPlayback::getCuPlaybackDomain,bo.getDomain())
        .eq(CuPlayback::getCuPlaybackAppName,bo.getApp())
        .eq(CuPlayback::getCuPlaybackStreamName,bo.getStream())
        .eq(CuPlayback::getCuPlaybackUrl,bo.getUri());
        Integer integer = playbackMapper.selectCount(queryWrapper);
        if (integer>0){
            return;
        }

        QueryWrapper<CuLive> liveWrapper = new QueryWrapper<>();
        liveWrapper.lambda().eq(CuLive::getCuLiveAppName,bo.getApp())
        .eq(CuLive::getCuLiveStreamName,bo.getStream());
        CuLive live = liveMapper.selectOne(liveWrapper);
        if (live==null){
            System.out.println("未找到直播间"+JSONObject.toJSONString(bo));
            return;
        }
        playback.setCuPlaybackAppName(bo.getApp());
        playback.setCuPlaybackDomain(bo.getDomain());
        playback.setCuPlaybackDuration(bo.getDuration());
        playback.setCuPlaybackStartTime(LocalDateTime.ofEpochSecond(bo.getStart_time(),0, ZoneOffset.ofHours(8)));
        playback.setCuPlaybackStopTime(LocalDateTime.ofEpochSecond(bo.getStop_time(),0, ZoneOffset.ofHours(8)));
        playback.setCuPlaybackStreamName(bo.getStream());
        playback.setCuPlaybackUrl(bo.getUri());
        playback.setCuPlaybackTitle(live.getCuLiveTitle());
        String s = MyUtils.syncImages(bo.getApp() + "/" + bo.getStream(), bo.getStart_time() + "");
        playback.setCuLiveCover(s);
        playbackMapper.insert(playback);
        System.out.println(JSONObject.toJSONString(bo));
    }
    //endregion

    //region 获得直播回放
    @Override
    public IPage<GetLiveBackDTO> getPlayBack(PagingCondition bo) {
        IPage<CuPlayback> page = new Page<>();
        page.setCurrent(bo.getCurrent()).setSize(bo.getSize());
        QueryWrapper<CuPlayback> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(CuPlayback::getCuPlaybackStartTime);
        page = playbackMapper.selectPage(page,queryWrapper);
        IPage<GetLiveBackDTO> result = new Page<>();
        BeanUtils.copyProperties(page,result);
        result.setRecords(JSONObject.parseArray(JSONObject.toJSONString(page.getRecords()),GetLiveBackDTO.class));
        return result;
    }
    //endregion

}
